package top.haijunit.work.service;

import com.baomidou.lock.DefaultLockFailureStrategy;
import com.baomidou.lock.DefaultLockKeyBuilder;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.lock.executor.RedissonLockExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.LockSupport;

/**
 * 测试锁
 *
 * @author zhanghaijun
 * @since 2024-09-10
 */
@Slf4j
@Service
public class LockTestService {


    @Lock4j(keys = "#blockTimeMillis + 'ms'")
    public String lock1(long blockTimeMillis) {
        log.info("执行方法lock1，当前线程:{}，block: {}ms ", Thread.currentThread().getName(), blockTimeMillis);
        LockSupport.parkNanos(blockTimeMillis * 1000000);
        return "执行方法lock1";
    }

    @Lock4j(keys = "#blockTimeMillis + 'MS'", keyBuilderStrategy = DefaultLockKeyBuilder.class, failStrategy = DefaultLockFailureStrategy.class)
    public String lock2(long blockTimeMillis) {
        log.info("执行方法lock2 , 当前线程:{}", Thread.currentThread().getName());
        LockSupport.parkNanos(blockTimeMillis * 1000000);
        return "执行方法lock2";
    }

    @Lock4j(keys = "#userId", acquireTimeout = 15000, expire = 1000, executor = RedissonLockExecutor.class)
    public String lock3(int userId) {
        log.info("执行方法lock3 , 当前线程:{}, userId: {}", Thread.currentThread().getName(), userId);
        LockSupport.parkNanos(2000000);
        return "执行方法lock3";
    }

    @Lock4j(keys = "#userId", acquireTimeout = 2000, expire = 15000, autoRelease = false, executor = RedissonLockExecutor.class)
    public String lock4(int userId) {
        log.info("执行方法lock4 , 当前线程:{}, userId: {}", Thread.currentThread().getName(), userId);
        LockSupport.parkNanos(2000000);
        return "执行方法lock4";
    }
}
